// component/com-cooperation/com-cooperation.js
import api from "./../../common/api";
import locationBehavior from "./../../behaviors/location";
import * as transferData from "./../../models/transferData";
import * as filterConfigs from "../../models/filterConfigs";
import constant from '../../common/constant';
import {
  getActiveStr
} from "../../utils/utilsNew";
import utils from "./../../utils/util";

const cityMap = require("./../../utils/city");
const app = getApp();

Component({
  behaviors: [locationBehavior],

  /**
   * 组件的配置
   */
  options: {
    styleIsolation: "apply-shared",
    addGlobalClass: true,
    pureDataPattern: /^_/,
  },

  /**
   * 组件的属性列表
   */
  properties: {
    tabConentIndex: {
      type: Number,
      value: 0,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    cooperationId: "", //当前电话中的合作id
    isVmShow: false, //虚拟电话弹层
    banners: [],
    cityName: "",
    cityCode: "",
    jjpageIndex:0, 
    upCooperationHouseNum: 0,
    consultingNum: 0,
    pageIndex: 0,
    pageSize: 10,
    houseList: [], //房源数据（根据搜索条件匹配的房源）
    hasMoreList: true, // 是否有更多房源（根据搜索条件匹配的房源）

    recommendList: [], // 推荐的房源
    hasMoreRecommend: true,
    recommendPageIndex: 0,
    search: {},
    defaultTabSelect: "SALES",
    tabSelect: "SALES",
    tabList: [{
        id: "SALES",
        label: "二手",
        add: "",
      },
      {
        id: "RENT",
        label: "出租",
        add: "",
      },
    ],
    filterMore0: {
      chooseType: 'SALES'
    },
    filterMore1: {},
    filterMore2: {},
    filterMore3: {},
    filterSalesList0: [{
      id: "chooseType",
      title: "类型",
      single: filterConfigs.rangeType,
      defaultValue: "SALES"
    }],
    filterSalesList1: [{
      id: "price",
      title: "价格区间（万）",
      input: {},
      multi: filterConfigs.rangeSalesPrice,
    }],
    filterSalesList2: [{
      id: "room",
      title: "户型",
      multi: filterConfigs.rangeHouseType,
    }],
    filterSalesList3: [{
        id: "lightSpot",
        title: "亮点",
        multi: filterConfigs.lightSpotType,
      },
      {
        id: "buildSize",
        title: "面积",
        multi: filterConfigs.rangeArea,
        input: {},
      }
    ],


    filterRentList0: [{
      id: "chooseType",
      title: "类型",
      single: filterConfigs.rangeType,
      defaultValue: "RENT"
    }],
    filterRentList1: [{
      id: "price",
      title: "价格区间（元）",
      input: {},
      multi: filterConfigs.rangeRentPrice,
    }],
    filterRentList2: [{
      id: "room",
      title: "户型",
      multi: filterConfigs.rangeHouseType,
    }],
    filterRentList3: [{
        id: "lightSpot",
        title: "亮点",
        multi: filterConfigs.lightSpotType,
      },
      {
        id: "buildSize",
        title: "面积",
        multi: filterConfigs.rangeArea,
        input: {},
      }
    ],
    filterDistrict: "", //过滤区域
    filterCondition: {}, //过滤筛选
    topList: [{
        id: "0",
        img: "../../images/myHouse.png",
        value: "我的房源",
        type: "my",
      },
      {
        id: "1",
        img: "../../images/whoCouse.png",
        value: "谁咨询过我",
        type: "seted",
      },
      {
        id: "2",
        img: "../../images/myCouse.png",
        value: "我咨询过的",
        type: "looked",
      },
      {
        id: "3",
        img: "../../images/myCredit.png",
        value: "认证信息",
        type: "credit",
      },
    ],
    comUnconfirmedRoom: false, //是否存在未确认的房态任务
    comUnconfirmedRoomNum: '', //未确认的房态数量
    isShowCertification: false, //展示--认证信息补充
    isShowSpecial: false,
    showBuCcertification: false, //判断是否展示 ----认证通过的弹窗
    lat: '', //纬度，范围为 -90~90，负数表示南纬
    lng: '', //经度，范围为 -180~180，负数表示西经   
    getRecommendJJRInfoList: [], //推荐附近的经纪人的数据
    isShowMore:'',//是否展示查看更多经纪人
    current:''
  },

  /**
   * 组件的数据监听
   */
  observers: {
    tabConentIndex() {
      if (this.data.tabConentIndex != 3) {
        return;
      }

      if (!(this.data.banners && this.data.banners.length)) {
        this.loadBanner();
      }
      this.summaryInfoByUserId();
      this.resetHouseData();
      this.checkCurrentCity().then(() => {
        this.loadHouse();
        this.loadBusinessCircles();
      });
      this.cooperationConfirmCount('first') // 临时需求--只要有未确认的房态就弹窗
      this.showBuCcertification()
    },
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function () {
      this.setData({
        headerHeight: app.globalData.navHeight,
      });
      this.myData = {
        pageEnterCount: 0,
      };
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 页面的生命周期
   */
  pageLifetimes: {
    show: function () {
      this.myData.pageEnterCount += 1;
      this.summaryInfoByUserId();
      this.loadBanner()
      
      if (this.myData.pageEnterCount > 1) {
        let refresh = transferData.getData("isRefreshCooperation");
        transferData.resetData("isRefreshCooperation");
        if (refresh) {
          this.resetHouseData();
          this.loadHouse();
        }
      }
      
      // 城市切换执行
      const cityName = this.data.cityName
      this.checkCurrentCity().then(() => {
        if (cityName && cityName != this.data.cityName) {
          app.globalData._wx_city = this.data.cityName
          this.resetHouseData();
          this.clearFilter();
          this.loadHouse();
          this.loadBusinessCircles();
        }
      });
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 加载轮播图
    loadBanner() {
      api.noticeBanner({}, (res) => {
        let list = res.data.content;
        let banners = list.map((item) => {
          return {
            bg: item.bg,
            butDesc: item.butDesc,
            desc: item.desc,
            sizeColor: item.sizeColor,
            title: item.title,
            param: item.linkUrl,
            type: item.type
          };
        });
        this.setData({
          banners,
          current:0,
        });
      });
    },

    // 点击轮播图
    onClickBanner(e) {
      let url = e.currentTarget.dataset.param
      wx.navigateTo({
        url
      })
    },

    // 点击查看更多
    onClickMore() {
      wx.navigateTo({
        url: "/pages/cooperation/user/user",
      });
    },

    // 加载合作概览
    summaryInfoByUserId() {
      return new Promise((resolve, reject) => {
        api.summaryInfoByUserId({}, (res) => {
          if (res && res.data && res.data.isSuccess) {
            let result = res.data.content || {};
            this.setData({
              upCooperationHouseNum: result.upCooperationHouseNum || 0,
              consultingNum: result.consultingNum || 0,
            });
            resolve();
          }
        });
      });
    },

    checkCurrentCity() {
      return new Promise((resolve, reject) => {
        this.getCityBe(true)
          .then((city) => {
            let cityCode = "";
            cityMap.cityObjs.forEach((item) => {
              if (item.city === city) {
                cityCode = item.code || "";
              }
            });
            if (cityCode) {
              this.setData({
                cityName: city,
                cityCode: cityCode,
              });
            } else {
              this.setData({
                cityName: "上海市",
                cityCode: "310000",
              });
            }
            resolve();
          })
          .catch(() => {
            this.setData({
              cityName: "上海市",
              cityCode: "310000",
            });
            resolve();
          });
      });
    },

    // 打电话展示/隐藏
    handleVmVisible(e) {
      this.setData({
        isVmShow: e.detail.visible,
        cooperationId: e.detail.cooperationId,
      });
    },

    // 搜索改变
    onSearchChange(e) {
      this.resetHouseData();
      this.setData({
        search: e.detail,
      });
      this.clearFilter();
      this.loadHouse();
    },

    // 筛选改变
    onFilterChange(e) {
      let name = e.currentTarget.dataset.name;
      let path = `filter${name}`;
      this.setData({
        [path]: e.detail.form,
      });

      setTimeout(() => {
        if (e.detail.form.chooseType == 'RENT') {
          this.setData({
            tabSelect: 'RENT',
            filterDistrict: {},
            filterMore1: {},
            filterMore2: {},
            filterMore3: {},
          });
        }
        if(e.detail.form.chooseType == 'SALES'){
          this.setData({
            tabSelect: 'SALES',
            filterDistrict: {},
            filterMore1: {},
            filterMore2: {},
            filterMore3: {},
          });
        }
        this.resetHouseData();
        this.loadHouse().then(()=>{
          wx.pageScrollTo({
            scrollTop: 195,
            duration: 100
          })
        });
      }, 300)
    },

    // 清空区域 筛选数据
    clearFilterData() {
      if (this.data.tabSelect === "SALES") {
        this.data.filterSalesList.forEach((item, i) => {
          const com = this.selectComponent(".list-filter-sales-" + i);
          if (com) {
            com.resetFilterData && com.resetFilterData();
          }
        });
      } else {
        this.data.filterRentList.forEach((item, i) => {
          const com = this.selectComponent(".list-filter-rent-" + i);
          if (com) {
            com.resetFilterData && com.resetFilterData();
          }
        });
      }
      this.setData({
        filterDistrict: {},
        filterMore1: {},
        filterMore2: {},
        filterMore3: {},
      });
    },

    // 加载更多
    onReachBottom() {
      this.loadHouse()
    },

    // 请求列表数据
    loadHouse() {
      let t = this;
      return new Promise((resolve, reject) => {
        if (!this.data.hasMoreList) {
          this.loadRecommend();
          resolve();
          return;
        }
        let params = this.generateParamer();
        api.searchHouseCooperationByResBlock(params,(res) => {
            if (res && res.data && res.data.isSuccess) {
              let result = res.data.content || {};
              let list = result.rows || [];
              let maxIndex = result.total;
              let formatList = list.map(this.formateHouseInfo);

              let currentIndex = this.data.pageIndex + 1;
              t.data.houseList.push(...formatList);
              t.setData({
                pageIndex: currentIndex,
                hasMoreList: maxIndex > currentIndex,
                houseList: t.data.houseList,
              });
              if (!this.data.hasMoreList) {
                this.loadRecommend();
                this.jjrComd()
              }

              resolve();
            } else {
              reject();
            }
          },
          () => {
            reject();
          }
        );
      });
    },

    generateParamer() {
      let t = this;
      let {
        pageIndex,
        pageSize,
        tabSelect,
        search,
        filterDistrict,
        cityName,
        cityCode,
        filterMore1,
        filterMore2,
        filterMore3,
      } = t.data;

      let currentIndex = pageIndex + 1;
      let newFilterMore1 = this.data.tabSelect=='SALES'?  (filterConfigs.parseFilterx(filterMore1)) : (filterConfigs.parseFilter(filterMore1));
      let newFilterMore2 = filterConfigs.parseFilter(filterMore2);
      let newFilterMore3 = filterConfigs.parseFilter(filterMore3);
      return {
        resblockId: search.type === "id" ? search.value : "",
        page: currentIndex,
        pageSize,
        delegationType: tabSelect,
        resblockName: search.type === "name" ? search.value : "",
        keyWords: search.type === "key" ? search.value : "",
        city: cityName,
        cityCode,
        areaCode: filterConfigs.parseAreaFilter(filterDistrict.district),
        bizCircleIds: filterConfigs.parseDistrictFilter(filterDistrict.district),
        filterCondition: {
          price: newFilterMore1.price,
          room: newFilterMore2.room,
          lightSpot: newFilterMore3.lightSpot,
          buildSize: newFilterMore3.buildSize,
        },
      };
    },

    // 推荐附近的经纪人
    jjrComd() {
      if (this.data.search.type=='id') {
        return new Promise((resolve, reject) => {
          const {jjpageIndex} = this.data
         let hdResblockId = this.data.search.value
          wx.showLoading({
            title: '加载中...',
          })
          let currentIndex = jjpageIndex + 1
          api.getRecommendJJRInfo({pageSize:3,hdResblockId,page: currentIndex}, (res) => {
            if (res && res.data && res.data.isSuccess) {
              let content = res.data.content.list
              let maxIndex = res.data.content.pages
              if (currentIndex === 1) {
                this.data.getRecommendJJRInfoList = [...content]
              } else {
                this.data.getRecommendJJRInfoList.push(...content)
              }
              this.setData({
                jjpageIndex: currentIndex,
                isShowMore: currentIndex >= maxIndex ? false : true,
                getRecommendJJRInfoList: this.data.getRecommendJJRInfoList
              })
              wx.hideLoading()
              resolve()
            }
          })
        })
      }
    },
    // 查看更多推荐经纪人
    lookMore(){
      this.jjrComd()
    },

    // 附近可合作房源
    loadRecommend() {
      const {
        type,
        value
      } = this.data.search;
      const {
        recommendPageIndex,
        hasMoreRecommend
      } = this.data;
      if (type !== "id" || !hasMoreRecommend) return;

      const curPage = recommendPageIndex + 1;
      let params = this.generateParamer();
      params.page = curPage;
      api.recommendCooperationHouse(params, ({
        data
      }) => {
        if (data && data.content && data.content.list && data.content.list) {
          const {
            list,
            pages
          } = data.content;
          let formatList = list.map((item) => {
            item = this.formateHouseInfo(item);
            item.isRecommend = true;
            return item;
          });
          this.setData({
            recommendList: this.data.recommendList.concat(formatList),
            hasMoreRecommend: pages > curPage && pages > 0,
            recommendPageIndex: curPage,
          });
        }
      }, () => {});
    },

    formateHouseInfo(item) {
      let price = item.totalPrices || 0;
      return {
        sceneType: "entrance",
        houseID: item.houseCooperationId || "",
        houseOldID: item.delId || "",
        houseName: item.resblockName || "",
        houseType: item.delegationType,
        houseImg: item.houseImg || "",
        houseArea: item.buildSize ? item.buildSize + "㎡" : "--",
        houseRoom: item.room || 0,
        houseHall: item.hall || 0,
        houseDistrict: item.area || "",
        housePrice: item.delegationType === "SALES" ? price / 10000 : price,
        houseIsVR: item.houSubType === 1 ? true : false,
        houseVRStatus: item.houSubTypeState || 0,
        houseIsCopy: item.copyHouseStatus || false,
        houseIsMy: item.myId || false,
        brokerName: getActiveStr(item.realName || "", 6),
        brokerStore: getActiveStr(item.storeAllName || "", 12),
        brokerUnionid: item.weChatUnionId || "",
        lightSpot: item.lightSpot || [],
        updateTime: item.updateTime ? utils.dateFormat(new Date(item.updateTime), "yyyy-MM-dd") : "",
        sortTime: item.sortTime ? utils.dateFormat(new Date(item.sortTime), "yyyy-MM-dd") : "",
        bizcirleName: item.bizcirleName || "",
        attestation: item.attestation,
        title: item.title,
        userId: item.userId
      };
    },

    resetHouseData(e) {
      this.setData({
        houseList: [],
        pageIndex: 0,
        jjpageIndex:0,
        hasMoreList: true,
        recommendList: [],
        getRecommendJJRInfoList:[],
        recommendPageIndex: 0,
        hasMoreRecommend: true,
      });
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0,
      });
    },

    // 合作发布按钮
    onJumpPublish() {
      this.verifyPublish().then(() => { //是否认证
        this.cooperationConfirmCount().then(() => { //是否有未确认房态
          this.authenticationInfo().then(() => { //服务宣言是否为空
            wx.gio('track', constant.RELEASE_FROM, {
              [constant.RELEASE_HOUSE_INFO]: '合作房源首页',
            })
            wx.navigateTo({
              url: "/pages/cooperation/publishIndex/publishIndex",
            });
          })
        });
      });
    },
    //  是否认证
    verifyPublish(tmp) {
      return new Promise((resolve, reject) => {
        let sessionUser = getApp().globalData.loginUserInfo.data.content.sessionUser;
        api.queryUserAuthInfo({
            userId: sessionUser.id
          }, (res) => {
            if (res && res.data && res.data.content) {
              let userInfo = res.data.content;
              if (userInfo.verified) {
                if (tmp === 'credit') {
                  wx.navigateTo({
                    url: '/pages/cooperation/authentication/authentication',
                  })
                }
                resolve();
              } else {
                wx.navigateTo({
                  url: '/pages/cooperation/editCertification/editCertification',
                })
                reject();
              }
            } else {
              reject();
            }
          },
          () => {
            wx.showToast({
              icon: "none",
              title: "网络错误，请稍后再试~",
            });
          }
        );
      });
    },

    // 0519合作房源优化  是否存在未确认的房态任务
    cooperationConfirmCount(tmp) {
      return new Promise((resolve, reject) => {
        api.cooperationConfirmCount({}, (res) => {
            if (res && res.data && res.data.isSuccess) {
              if (res.data.content !== 0) {
                if (tmp === 'first') {
                  this.setData({
                    comUnconfirmedRoomNum: res.data.content,
                    comUnconfirmedRoom: true,
                    isShowSpecial: true
                  })
                  reject();
                } else {
                  this.setData({
                    comUnconfirmedRoom: true,
                    isShowSpecial: false
                  });
                  reject();
                }

              } else {
                resolve();
              }
            } else {
              reject();
            }
          },
          () => {
            wx.showToast({
              icon: "none",
              title: "网络错误，请稍后再试~",
            });
          }
        );
      });
    },

    //服务宣言是否为空
    authenticationInfo() {
      return new Promise((resolve, reject) => {
        api.authenticationInfo({}, (res) => {
          if (res && res.data && res.data.isSuccess) {
            let content = res.data.content.declaration
            if (content === '') {
              this.setData({
                isShowCertification: true
              })
              reject();
            } else {
              resolve();
            }
          } else {
            wx.showToast({
              title: "获取认证信息失败",
              icon: "none",
              duration: 1000,
            });
            reject();
          }
        })
      })
    },
    // 以后再说
    closeButX() {
      this.setData({
        isShowCertification: false
      })
    },
    // 填写or立即补充
    immediatelyAddedX() {
      wx.navigateTo({
        url: '/pages/cooperation/authentication/authentication?cooperation=true',
      })
      this.setData({
        isShowCertification: false
      })
    },

    // 区域筛选的数据
    loadBusinessCircles() {
      return new Promise((resolve, reject) => {
        this.getWxLocationBe()
          .then((res) => {
            this.setData({
              lat: res.latitude,
              lng: res.longitude
            })
            this.getCirclesList()
            resolve();
          })
          .catch(() => {
            this.getCirclesList()
            reject();
          })
      })
    },
    getCirclesList() {
      return new Promise((resolve, reject) => {
        const {
          cityCode,
          lat,
          lng,
        } = this.data;
        api.getBizcirclesCooperationHouse({
            cityCode,
            lat,
            lng,
            isCooperation: "1"
          }, (res) => {
            this.setData({
              filterDistrictOptions: [{
                id: "district",
                cascader: filterConfigs.formatDistrictOptions(res.data.content),
              }, ],
            });
            resolve();
          },
          () => {
            reject();
          }
        );
      });
    },


    clearFilter() {
      this.setData({
        filterMore1: {},
        filterMore2: {},
        filterMore3: {},
        filterDistrict: {},
      });
      const child = this.selectComponent("#dropdowns");
      child && child.onClear();
    },

    // ------------------------合作房源0519优化---------------------------
    cooperativeHouse(e) {
      let type = e.currentTarget.dataset.type;
      switch (type) {
        case "my": //我的房源
          wx.navigateTo({
            url: "/pages/cooperation/user/user?type=publish&name=首页",
          });
          break;
        case "seted": //谁咨询过我
          wx.navigateTo({
            url: "/pages/cooperation/cooperativeAdvisory/cooperativeAdvisory",
          });
          break;
        case "looked": //我咨询过的
          wx.navigateTo({
            url: "/pages/cooperation/user/user?type=consult",
          });
          break;
        case "credit": //认证信息
          this.verifyPublish('credit')
          break;
      }
    },

    // 点击前往确认
    _confirmEvent(e) {
      this.setData({
        comUnconfirmedRoom: false,
      });
      wx.navigateTo({
        url: "/pages/cooperation/houseStatusUpdate/houseStatusUpdate",
      });
    },
    // 暂不确认
    _cancelEvent(e) {
      this.setData({
        comUnconfirmedRoom: false,
      });
    },

    //======================================2021-07-27================================================
    // 认证完成且没有发房 -----第一次来到合作房源出现此弹窗 -----关闭按钮
    closeBuCcertification() {
      this.setData({
        showBuCcertification: false
      })
    },
    // 认证完成且没有发房 -----第一次来到合作房源出现此弹窗 -----立即发房
    confirmBuCcertification() {
      this.setData({
        showBuCcertification: false
      })
      wx.gio('track', constant.RELEASE_FROM, {
        [constant.RELEASE_HOUSE_INFO]: '发房引导弹窗',
      })
      wx.navigateTo({
        url: "/pages/cooperation/publishIndex/publishIndex",
      });
    },

    // 判断是否展示 ----认证通过的弹窗
    showBuCcertification() {
      return new Promise((resolve, reject) => {
        let sessionUser = getApp().globalData.loginUserInfo.data.content.sessionUser;
        api.showWindow({
          userId: sessionUser.id
        }, (res) => {
          if (res && res.data && res.data.content) {
            let show = res.data.content.show
            if (show) {
              this.setData({
                showBuCcertification: true
              })
              resolve();
            }
          } else {
            reject();
          }
        });
      });
    },

    //  点击定位  且没有授权位置信息
    myEventListener(e) {
      if (e.detail.currentTarget.dataset.item.value === "location") {
        this.getWxLocationBe()
          .then((res) => {})
          .catch(() => {
            wx.getSetting({
              success: (res) => {
                if (!res.authSetting["scope.userLocation"]) {
                  this.openConfirm();
                }
              },
            });
          })
      }
    },
    openConfirm() {
      let that = this
      wx.showModal({
        content: "检测到您没打开定位权限，是否去设置打开？",
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                if (res.authSetting['scope.userLocation']) {
                  that.getWxLocationBe()
                    .then((res) => {
                      that.setData({
                        lat: res.latitude,
                        lng: res.longitude
                      })
                      that.getCirclesList()
                        .then(() => {
                          let value = that.data.filterDistrictOptions[0].cascader[0].children[1].value //获取区域code
                          let filterDistrict = {
                            district: [
                              ["area", value, "INFINTE"]
                            ]
                          }
                          that.setData({
                            filterDistrict,
                          })
                        })
                    })
                }
              },
            });
          }
        },
      });
    },
    //点击筛选组件---屏幕滚动
    scrollClick(e) {
      wx.pageScrollTo({
        scrollTop: 195,
        duration: 300
      })
    }
  },
});